//
//  MineView.swift
//  todoios
//
//  Created by qianli on 2025/4/14.
//

import Foundation
import UIKit
import SwiftyUserDefaults
import SVGKit //显示svg图标

class MineView: UIView {
    var closeBlock:os_block_t?
    var tapBlock:((_ itemindex:Int)->Void)?
    
    private var yYfZnCKFmQRnxYeI:UIImageView = UIImageView()
    private var jXpbrxMcMxCQdsDc: UILabel?
    private var jAJnPmfbfVR66Glj: UILabel?
    private var ZYRF5ZPyDdU9kORK: UILabel?
    private var E9uYJ0lsYpyoYQLV: UIButton?
    private var RvSFR78Dkj1NHUUh:UILabel = UILabel()
    private var NUXrzDN3xyo0sLDs:UILabel = UILabel()
    private var UWH069Bn4slSwRv8 = UILabel()
    private var dYQdT1ccZ0RXFMhb:GradientBtn?
    private var dmWd72pIs2TPJszL:GradientBtn?
    
    deinit {
        QianliUniversalFunc.QianliLog("------MineView.deinit")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.GHL4Rhb91XYBer27()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func GHL4Rhb91XYBer27(){
        self.backgroundColor = .black.withAlphaComponent(0.65)
        let rightView = UIView(frame: CGRect(x: qianli_pm_width-100, y: 0, width: 100, height: qianli_pm_height))
        self.addSubview(rightView)
        rightView.tap_With_Block {[weak self] in
            self?.backgroundColor = .black.withAlphaComponent(0)
            UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {[weak self] in
                 self?.frame.origin.x = -qianli_pm_width//从右向左退出
            } completion: { _ in
                if let mineview = self{
                    for perView in mineview.subviews {
                        perView.removeFromSuperview()
                    }
                    mineview.removeFromSuperview()
                }
                self?.closeBlock?()
            }
        }
        
        let contentWidth = qianli_pm_width-100
        let leftContent = UIView(frame: CGRect(x: 0, y: 0, width: contentWidth, height: qianli_pm_height))
        self.addSubview(leftContent)
        leftContent.backgroundColor = .secondarySystemBackground
        
        let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
        let labelBarTitle = UILabel(frame: CGRect(x: 15, y: topSpace-40, width: contentWidth, height: 30))
        leftContent.addSubview(labelBarTitle)
        labelBarTitle.text = LocalizedString("User Center")
        labelBarTitle.font = .boldSystemFont(ofSize: 18)
        labelBarTitle.textColor = .label
        
        let avatarWidth = 70.0
        let titleBar = UIView(frame: CGRect(x: 0, y: topSpace+15, width: leftContent.bounds.width, height: avatarWidth))
        leftContent.addSubview(titleBar)
        
//头像
        self.yYfZnCKFmQRnxYeI = UIImageView(frame: CGRect(x: 15, y: 0, width: avatarWidth, height: avatarWidth))
        titleBar.addSubview(self.yYfZnCKFmQRnxYeI)
        self.yYfZnCKFmQRnxYeI.layer.cornerRadius = avatarWidth / 2
        self.yYfZnCKFmQRnxYeI.clipsToBounds = true
        self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
        
        
//username
        let iLeft = 15+avatarWidth+10
        self.jXpbrxMcMxCQdsDc = UILabel(frame: CGRect(x: iLeft, y: 0, width: contentWidth-iLeft-10, height: 25))
        if let labeluser = self.jXpbrxMcMxCQdsDc{
            titleBar.addSubview(labeluser)
            labeluser.textColor = .label
            labeluser.font = .systemFont(ofSize: 15)
            let username = Defaults[\.username]
            labeluser.text = username.isEmpty ? LocalizedString("UNLOGIN") : username //"尚未登录"
        }
//邀请码
        self.jAJnPmfbfVR66Glj = UILabel(frame: CGRect(x: iLeft, y: 30, width: 100, height: 20))
        if let labelinvite = self.jAJnPmfbfVR66Glj{
            titleBar.addSubview(labelinvite)
            let inviteTitle =  "\(LocalizedString("INVITECODE"))：" + Defaults[\.invitationCode] //邀请码
            labelinvite.text = inviteTitle
            labelinvite.font = .systemFont(ofSize: 13)
            labelinvite.textColor = .secondaryLabel
            labelinvite.isHidden = true
 
            self.E9uYJ0lsYpyoYQLV = UIButton(frame: CGRect(x: iLeft+labelinvite.bounds.width+10, y: 30, width: 40, height: 20))
            if let btncopy = self.E9uYJ0lsYpyoYQLV{
                titleBar.addSubview(btncopy)
                let inviteCode = Defaults[\.invitationCode]
                let copytitle = inviteCode.isEmpty ? LocalizedString("LOGIN") : LocalizedString("COPY")
                btncopy.setTitle(copytitle, for: .normal)
                btncopy.titleLabel?.font = .systemFont(ofSize: 13)
                btncopy.setTitleColor(UIColor(hexString: "#3762FF"), for: .normal)
                btncopy.isHidden = true
                btncopy.touch_With_Block {[weak self] sender in
                    QianliVibrateEnum.light.vibrate()
                    if (inviteCode.isEmpty){
                        self?.tapBlock?(11)
                    }else{
                        UIPasteboard.general.string = inviteCode
                        self?.Qianli_Toast(LocalizedString("INVITECODE COPYED"))//"邀请码已复制!"
                    }
                }
            }
        }
        let btnH = 32.0
        let btnW = 70.0
        let btnY = self.yYfZnCKFmQRnxYeI.frame.maxY - btnH
        titleBar.addSubview(self.UWH069Bn4slSwRv8)
        self.UWH069Bn4slSwRv8.frame = CGRect(x: iLeft, y:btnY-10 , width: 2*btnW, height: btnH)
        self.UWH069Bn4slSwRv8.textColor = .secondaryLabel
        self.UWH069Bn4slSwRv8.font = .systemFont(ofSize: 13)
        let myLevel = Defaults[\.memberLevel]
        let levelStr = "\(LocalizedString("MEMBER LEVEL"))：" + QianliUtils.shared.getLevel(level:myLevel)
        HaBjqrPksgDI8DHj(on: self.UWH069Bn4slSwRv8, with: levelStr, and: "\(LocalizedString("MEMBER LEVEL"))：", and: 13.0)
        
        self.dYQdT1ccZ0RXFMhb = GradientBtn.init(frame: CGRect(x: iLeft, y:btnY , width: btnW, height: btnH),title: LocalizedString("REGISTER"))
        if let regBtn = self.dYQdT1ccZ0RXFMhb{
            titleBar.addSubview(regBtn)
            regBtn.touch_With_Block { [weak self](sender) in
                self?.tapBlock?(90)
            }
        }
        self.dmWd72pIs2TPJszL = GradientBtn.init(frame: CGRect(x: iLeft + btnW + 15.0, y: btnY, width: btnW, height: btnH),title: LocalizedString("LOGIN"))
        if let lgBtn = self.dmWd72pIs2TPJszL{
            titleBar.addSubview(lgBtn)
            lgBtn.touch_With_Block { [weak self](sender) in
                self?.tapBlock?(91)
            }
        }
        
        if Defaults[\.isGuset]{
            self.dmWd72pIs2TPJszL?.isHidden = false
            self.dYQdT1ccZ0RXFMhb?.isHidden = false
            self.UWH069Bn4slSwRv8.isHidden = true
        }else{
            self.dmWd72pIs2TPJszL?.isHidden = true
            self.dYQdT1ccZ0RXFMhb?.isHidden = true
            self.UWH069Bn4slSwRv8.isHidden = false
        }
        
        let btnArrow = UIButton(frame: CGRect(x: contentWidth-10-32, y: titleBar.bounds.height/2-16, width: 32, height: 32))
        titleBar.addSubview(btnArrow)
        
        btnArrow.setImage("qianli_row_next".qianli_R_image, for: .normal)
        btnArrow.touch_With_Block {[weak self] sender in
//去用户详情页面
                self?.tapBlock?(11)
        }
        
        titleBar.tap_With_Block {[weak self] in
            self?.tapBlock?(11)
        }
        
        
//菜单
        let lineH = CALayer() //分隔线
        leftContent.layer.addSublayer(lineH)
        lineH.frame = CGRect(x: 0, y: titleBar.frame.maxY + 20, width: contentWidth, height: 0.5)
        lineH.backgroundColor = UIColor.systemGray.cgColor
        
        let scrollTop = titleBar.frame.maxY + 21
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: scrollTop, width: contentWidth, height: qianli_pm_height-scrollTop-140))
        leftContent.addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = false
        XTV2nW4A22cdzV6X(scrollView)
        
//底部续费会员及版本号
        self.ZYRF5ZPyDdU9kORK = UILabel(frame: CGRect(x: 15, y: qianli_pm_height - 130 - 60, width: contentWidth-30, height: 60))
        if let labelexptime = self.ZYRF5ZPyDdU9kORK{
            leftContent.addSubview(labelexptime)
            labelexptime.textColor = .label
            labelexptime.textAlignment = .center
            labelexptime.font = .boldSystemFont(ofSize: 15)
            let iso8601String = Defaults[\.memberexpiryat]
            labelexptime.text = isoDate2Formatdate(iso8601String) + " \(LocalizedString("EXPIRE"))"//到期
        }
        
        let vipButton = GradientBtn.init(frame: CGRect(x: 15, y: qianli_pm_height-130, width: contentWidth-30, height: 40),title: LocalizedString("RENEW MEMBERSHIP"))//续费会员
        leftContent.addSubview(vipButton)
        vipButton.layer.cornerRadius = 10
        vipButton.qianli_button_image(image: "qianli_member_bar".qianli_R_image,imgSize: CGSize(width: 24, height: 24),imgPadding: 15, imagePlacement: .leading,font: .systemFont(ofSize: 16))
        vipButton.touch_With_Block { [weak self](sender) in
            QianliVibrateEnum.selection.vibrate()
            self?.tapBlock?(99)
        }
        
        let verLabel = UILabel(frame: CGRect(x: contentWidth/2 - 100, y: qianli_pm_height - 70, width: 200, height: 20))
        leftContent.addSubview(verLabel)
        verLabel.textColor = .secondaryLabel
        verLabel.font = .systemFont(ofSize: 12)
        verLabel.textAlignment = .center
        if let infoDict = Bundle.main.infoDictionary{
            if let version = infoDict["CFBundleShortVersionString"] as? String{
                if let buildVer = infoDict["CFBundleVersion"] as? String{
                    verLabel.text = String(format: "Ver \(version).\(buildVer)")
                }
            }
        }
        
        self.perform(#selector(GXwrjdpULOsWeoiB), with: nil, afterDelay: 1.0)
        
    }
    
    @objc func GXwrjdpULOsWeoiB(){
        if Defaults[\.isGuset]{
            self.yYfZnCKFmQRnxYeI.image = "qianli_slider_guesthead".qianli_R_image
            return
        }
        
        if Defaults[\.avatar].isEmpty{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
            return
        }
        
        if let imageUrl = URL(string: LoginViewModel.shared.url_JKou + Defaults[\.avatar]){
            if imageUrl.pathExtension.lowercased() == "svg" { //svg类型图标特殊处理
//              imgHeader.image =  SVGKImage(contentsOf: imageUrl).uiImage //同步加载SVG图片
                let task = URLSession.shared.dataTask(with: imageUrl) { [weak self] (data, response, error) in
                            if let error = error {
                                if let self = self{
                                    QianliUniversalFunc.QianliLog("Error loading image: \(error)")
                                    self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                                }
                                return
                            }

                            guard let data = data else {
                                if let self = self{
                                    QianliUniversalFunc.QianliLog("No data received")
                                    self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                                }
                                return
                            }

                            // 在后台线程解析 SVG 数据
                            DispatchQueue.global().async {
                                if let svgImage = SVGKImage(data: data) {
                                    let uiImage = svgImage.uiImage
                                    // 回到主线程更新 UI
                                    DispatchQueue.main.async {
                                        if let self=self{
                                            self.yYfZnCKFmQRnxYeI.image = uiImage
                                        }
                                    }
                                }
                            }
                        }
                        // 启动任务
                        task.resume()
            }else{
                self.yYfZnCKFmQRnxYeI.sd_setImage(with: imageUrl, placeholderImage: nil) { [weak self](image, error, cacheType, url) in
                    if error != nil || image == nil,let self = self{
                        self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                    }
                }
            }
        }else{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
        }
    }
    
    private func XTV2nW4A22cdzV6X(_ scrollView:UIScrollView){
        var iTop = 15.0
        let iWidth = scrollView.bounds.width
        let imgHeight = 20.0
        for slideMenu in QianliConfig.SlideMenuList {
            if slideMenu.id==3 && LoginViewModel.shared.darwin_reviewing{
                continue
            }
            let itemH = 40.0
            let itemW = iWidth - 30
            let item = MineItem(frame: CGRect(x: 15, y: iTop, width: itemW, height: itemH), title: slideMenu.name, imgName: slideMenu.iconName, imgHeight: imgHeight)
            scrollView.addSubview(item)
            let menuId=slideMenu.id
            
            if menuId == 7{
                self.NUXrzDN3xyo0sLDs = UILabel(frame: CGRect(x: itemW-146-20, y: itemH/2-24/2, width: 146, height: 24))
                item.addSubview(self.NUXrzDN3xyo0sLDs)
                let fcache = QianliUniversalFunc.sharedInstance.fileSizeOfAllCache()
                let bindstr = LocalizedString("Can Bind")
                self.NUXrzDN3xyo0sLDs.text =  "\(bindstr) \(Defaults[\.maxBindCount]) \(LocalizedString("Devices"))"
                if let userDeviceList = UserInfoViewModel.shared.userDeviceList{
                    if let data = userDeviceList.data{
                        let str = LocalizedString("Has Bind")
                        self.NUXrzDN3xyo0sLDs.text =  "\(str) \(data.count) \(LocalizedString("Devices"))"
                    }
                }
                self.NUXrzDN3xyo0sLDs.textColor = .secondaryLabel
                self.NUXrzDN3xyo0sLDs.textAlignment = .right
                self.NUXrzDN3xyo0sLDs.font = .systemFont(ofSize: 13)
                item.tap_With_Block {[weak self] in
                    if fcache>0{
                        self?.tapBlock?(menuId)
                    }
                }
            }
            else if menuId == 8{
                self.RvSFR78Dkj1NHUUh = UILabel(frame: CGRect(x: itemW-146-20, y: itemH/2-24/2, width: 146, height: 24))
                item.addSubview(self.RvSFR78Dkj1NHUUh)
                let fcache = QianliUniversalFunc.sharedInstance.fileSizeOfAllCache()
                self.RvSFR78Dkj1NHUUh.text =  String(format: "%.2f M", fcache)
                self.RvSFR78Dkj1NHUUh.textColor = .secondaryLabel
                self.RvSFR78Dkj1NHUUh.textAlignment = .right
                self.RvSFR78Dkj1NHUUh.font = .systemFont(ofSize: 13)
                item.tap_With_Block {[weak self] in
                    if fcache>0{
                        self?.tapBlock?(menuId)
                    }
                }
            }
            else if menuId == 9{ //触感开关
                let btn = UIButton(frame: CGRect(x: itemW-46-15, y: itemH/2-24/2, width: 46, height: 24))
                item.addSubview(btn)
                let optImage = Defaults[\.enableQainliImpactFeedback] ? "qianli_switch_h".qianli_R_image : "qianli_switch_n".qianli_R_image
                btn.setImage(optImage, for: .normal)
                btn.tap_With_Block {[weak btn] in
                    if Defaults[\.enableQainliImpactFeedback] {
                        Defaults[\.enableQainliImpactFeedback] = false
                        btn?.setImage("qianli_switch_n".qianli_R_image, for: .normal)
                    }else{
                        Defaults[\.enableQainliImpactFeedback] = true
                        btn?.setImage("qianli_switch_h".qianli_R_image, for: .normal)
                        QianliVibrateEnum.light.vibrate()
                    }
                    
                }
            }else{
                item.tap_With_Block {[weak self] in
                    self?.tapBlock?(menuId)
                }
            }
            
            iTop = item.frame.maxY + 10.0
        }
        
        scrollView.contentSize = CGSize(width: iWidth, height: iTop)
    }
    
    func PefGxtaeiGhiGKAO(){
        let fcache = QianliUniversalFunc.sharedInstance.fileSizeOfAllCache()
        self.RvSFR78Dkj1NHUUh.text =  String(format: "%.2f M", fcache)
    }
    
    func uieXcVRJzNjKLXPF(){
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        GXwrjdpULOsWeoiB()
        
        if let labeluser = self.jXpbrxMcMxCQdsDc{
            let username = Defaults[\.username]
            labeluser.text = username.isEmpty ? LocalizedString("UNLOGIN") : username //尚未登录
        }
        if let labelinvite = self.jAJnPmfbfVR66Glj{
            let inviteTitle = "\(LocalizedString("INVITECODE"))：" + Defaults[\.invitationCode] //邀请码
            labelinvite.text = inviteTitle
        }
        if let labelexptime = self.ZYRF5ZPyDdU9kORK{
            let iso8601String = Defaults[\.memberexpiryat]
            labelexptime.text = isoDate2Formatdate(iso8601String) + " \(LocalizedString("EXPIRE"))"//到期
        }
        if let btncopy = self.E9uYJ0lsYpyoYQLV{
            let inviteCode = Defaults[\.invitationCode]
            let copytitle = inviteCode.isEmpty ? LocalizedString("LOGIN") : LocalizedString("COPY")
            btncopy.setTitle(copytitle, for: .normal)
        }
        
        if Defaults[\.isGuset]{
            self.dmWd72pIs2TPJszL?.isHidden = false
            self.dYQdT1ccZ0RXFMhb?.isHidden = false
            self.UWH069Bn4slSwRv8.isHidden = true
        }else{
            self.dmWd72pIs2TPJszL?.isHidden = true
            self.dYQdT1ccZ0RXFMhb?.isHidden = true
            
            let myLevel = Defaults[\.memberLevel]
            let levelStr = "\(LocalizedString("MEMBER LEVEL"))：" + QianliUtils.shared.getLevel(level:myLevel)
            HaBjqrPksgDI8DHj(on: self.UWH069Bn4slSwRv8, with: levelStr, and: "\(LocalizedString("MEMBER LEVEL"))：", and: 13.0)
            self.UWH069Bn4slSwRv8.isHidden = false
        }
        
    }
    
    func HaBjqrPksgDI8DHj(on label:UILabel,with newTitle:String,and normalText:String,and fontsize:CGFloat){
//富文本
        let myMutableString = NSMutableAttributedString(
                    string: newTitle,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontsize),
                                 NSAttributedString.Key.foregroundColor:UIColor(hexString: "#3964ff")])
        let range_N:NSRange = (newTitle as NSString).range(of:normalText)
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.secondaryLabel], range: range_N)
        label.attributedText = myMutableString
    }
}
